require 'eeepub/lib/eeepub'
require 'erb'
require 'kconv'
require 'date'

include ERB::Util


# Creates epub output
class EpubBuilder

  def add_albums(albums)
    @hash=Hash.new{ |hash,key| hash[key]=[] } unless @hash
    albums.each do |album|
      unless album.lyrics.size==0
        @hash[album.artist.upcase.strip] << album
      end
    end
  end

  def to_epub name
    ext=File.extname(name)
    basename=File.basename(name,ext)
    @html_files=[]
    Dir.mktmpdir do |base_dir|
      build_pages base_dir
      css=File.dirname(__FILE__)+"/../../templates/style001.css"
      logo=File.dirname(__FILE__)+"/../../templates/logo.png"
      nav1=build_nav
      files=[]
      @html_files.each do |file|
        files << {file=>'pages'}
      end
      files << {css=>'Styles'}
      files << {logo=>'Images'}
      epub = EeePub.make do
        title       basename
        creator     'lyrics-ebook'
        publisher   'maner'
        date        Date.today.to_s
        identifier  'http://example.com/book/foo', :scheme => 'URL'
        uid         'http://example.com/book/foo'
        files files
        nav nav1
        guide  [
          {:type => 'toc', :title => 'Table of Contents', :href => 'pages/artists.xhtml'},
          {:type => 'cover', :title => 'Cover', :href => 'pages/cover.xhtml'}
        ]
      end
      name=name+".epub" if ext==""
      epub.save(name)
      puts "Created "+name
    end
  end

  private 

  def build_pages base_dir
    @data=@hash.to_a.sort!
    @data.each{|r| r[1].sort! }
    pages_dir=File.join(base_dir,"pages")
    Dir.mkdir(pages_dir)
    build_html('cover',pages_dir)
    build_html('artists',pages_dir)
    @data.each_with_index do |art_albums,index|
      @art_name,@albums=art_albums
      build_html('art_album_'+index.to_s,pages_dir,'art_album_')
    end
  end

  def build_nav
    nav=[]
    @data.each_with_index do |art_albums,index|
      art_aname="pages/art_album_#{index}.xhtml"
      art_label=art_albums[0]
      nav1=[]
      art_albums[1].each_with_index do |album, index_album|
        album_aname="pages/art_album_#{index}.xhtml#album_#{index_album}"
        nav1 << {:label => album.title, :content =>album_aname}
      end
      nav << {:label => art_label, :content => art_aname, :nav => nav1}
    end
    [
     {:label => "Cover", :content =>'pages/cover.xhtml'},
     {:label => "Content", :content =>'pages/artists.xhtml', :nav => nav}
    ]
  end

  def build_html name, basedir, template_name=nil
    template_name=name if template_name.nil?
    template=read_template(template_name)
    html=ERB.new(template)
    res=html.result(binding)
    html_file=File.join(basedir, name+'.xhtml')
    File.open(html_file,'w') do |f|
      f << res.toutf8
    end
    @html_files << html_file
  end

  def read_template name
    template_file=File.dirname(__FILE__)+"/../../templates/"+name+".erb.xhtml"
    template=""
    IO.foreach(template_file) {|line| template << line }
    template
  end
    
end

